package com.haruhi.bot.service;

import com.alibaba.fastjson.JSONObject;
import com.haruhi.bot.entity.bot.PixPicture;
import com.haruhi.bot.entity.dto.PixPictureCondition;
import com.haruhi.bot.entity.haruhi.Wallpaper;
import com.haruhi.bot.mapper.mysql.HaruhiDBMapper;
import com.haruhi.bot.mapper.postgresql.PixPictureMapper;
import com.haruhi.bot.utils.CommonUtil;
import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PixPictureService {


    @Autowired
    private PixPictureMapper pixPictureMapper;

    @Autowired
    private HaruhiDBMapper haruhiDBMapper;

    @Value("${upload.file.path}")
    private String path;

    private static String tomcatBaseUrl = "http://120.24.224.57:8080";


    public List<Wallpaper> getHaruhiWallpaper(){
        return haruhiDBMapper.selectList();
    }

    public List<PixPicture> getBotPixPicture(){
        return pixPictureMapper.selectList();
    }

    /**
     * 判断图片是否已经存在
     * @param md5
     * @return
     */
    public Integer countPix(String md5){
        return pixPictureMapper.countByImageP(md5);
    }


    public void insertBotPix(PixPicture picture){
        pixPictureMapper.insertPiXPicture(picture);
        haruhiDBMapper.updateIsPut(true, picture.getImgP());
    }

    public List<PixPicture> queryPixPicture(PixPictureCondition condition){
        return pixPictureMapper.select(condition);
    }

    public List<PixPicture> allPix(){
        return pixPictureMapper.selectList();
    }

    /**
     * 删除重复图片
     */
    public void deleteRepeatPicture(){
        List<PixPicture> pixPictures = pixPictureMapper.selectRepeatPicture();
        if(pixPictures != null && pixPictures.size() > 0){
            log.info("task执行删除重复图片开始,重复数据{}条", pixPictures.size());
            // 删除全部 by ids
//            pixPictureMapper.deleteByIds(pixPictures);
            // 根据对象的一个属性去重，取最后一个对象
            List<PixPicture> newList = pixPictures.stream().collect(Collectors.collectingAndThen
                    (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                            (PixPicture::getImgP))), ArrayList::new));

            // by img_p (md5)
            int i = pixPictureMapper.deleteByImgP(newList);
            log.info("删除了{}条",i);

            // 添加
            int i1 = pixPictureMapper.insertBatch(newList);
            log.info("添加了{}条",i1);

            pixPictures.removeAll(newList);
            for (PixPicture pixPicture : pixPictures) {
                CommonUtil.deleteFile(pixPicture.getTitle());
            }

            log.info("删除重复数据完成");
        }

    }


    public void upload(String name,InputStream is,String tag){

        File f = new File(path);
        String md5 = "";
        if(!f.exists()){
            f.mkdirs();
        }
        String originalFilename = name;
        String newFileName = CommonUtil.getNewFileName(originalFilename);
        File file1 = new File(f, newFileName);

        OutputStream os = null;
        try {

            os = new FileOutputStream(file1);

            byte[] buff = new byte[1024 * 10];
            int len = 0;
            while ((len = is.read(buff)) != -1){
                os.write(buff,0,len);
            }


            md5 = CommonUtil.getMd5(file1);
            PixPicture item = new PixPicture();
            item.setTags(tag);
            item.setPid(1);
            item.setView(1);
            item.setIsR18(false);
            item.setUid(1);
            String savePath = file1.toString();
            item.setTitle(savePath);
            item.setAuthor("uploader");
            item.setHeight(1);
            item.setWidth(1);
            item.setBookmarks(1);
            item.setImgP(md5);
            item.setImgUrl(tomcatBaseUrl + "/upload/bot/" + newFileName);
            pixPictureMapper.insertPiXPicture(item);
            log.info("本次上传成功,文件名:{},tag:{},保存路径:{}",originalFilename,tag, savePath);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("保存图片发生错误:{}",e.getMessage());
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("关闭输入流异常:{}",e.getMessage());
            }
            try {
                os.close();
            } catch (IOException e) {
                log.error("关闭输出流异常:{}",e.getMessage());
            }
        }

    }

}
